<template>
  <div class="h-full w-full flex flex-col justify-between">
    <div class="form px-[15px] pt-[15px] border-bottom">
      <el-form>
        <el-row :gutter="12">
          <el-col :span="3">
            <el-form-item>
              <el-input v-model="form.name" placeholder="用户名/备注" />
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select class="!w-full" v-model="form.status">
                <el-option
                  v-for="item in statusType"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="3">
            <el-form-item>
              <el-select class="!w-full" v-model="form.type">
                <el-option
                  v-for="item in updownType"
                  :key="item.value"
                  :label="item.name"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <div class="w-full flex justify-between">
                <el-date-picker
                  v-model="form.date"
                  type="daterange"
                  unlink-panels
                  range-separator="－"
                  start-placeholder="选择开始时间"
                  end-placeholder="选择结束时间"
                  :disabled-date="disableFutureDates"
                />
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item>
              <el-button type="primary" @click.stop="search">搜索</el-button>
              <el-button type="danger" @click.stop="handleRefresh">清空</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <div class="px-[15px] pt-[10px]">
      <el-button type="success" @click="handleBtnDate('today')">今天</el-button>
      <el-button type="success" @click="handleBtnDate('yesterday')">昨天</el-button>
      <el-button type="success" @click="handleBtnDate('thisWeek')">本周</el-button>
      <el-button type="success" @click="handleBtnDate('lastWeek')">上周</el-button>
      <el-button type="success" @click="handleBtnDate('thisMonth')">本月</el-button>
      <el-button type="success" @click="handleBtnDate('lastMonth')">上月</el-button>
    </div>
    <div class="grow-[1] h-0 mx-[15px] mt-[10px]">
      <el-table
        v-loading="state.loading"
        ref="elTableRef"
        :data="list"
        style="width: 100%"
        height="100%"
        border
        stripe
        fit
      >
        <template #empty>
          <ui-empty />
        </template>
        <el-table-column prop="Name" align="center" label="用户名" show-overflow-tooltip />
        <el-table-column prop="Note" align="center" label="会员备注" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Note || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="Nickname" align="center" label="昵称" show-overflow-tooltip>
          <template #default="{ row }: TableItem">
            {{ row.Note || "--" }}
          </template>
        </el-table-column>
        <el-table-column prop="Type" align="center" label="类型" min-width="80">
          <template #default="{ row }: TableItem">
            <el-button
              v-if="typeMap[row.Type]?.type"
              :type="typeMap[row.Type]?.type"
              size="small"
              >{{ typeMap[row.Type]?.text }}</el-button
            >
            <div v-else></div>
          </template>
        </el-table-column>
        <el-table-column
          prop="Amount"
          align="center"
          label="积分"
          min-width="90"
          show-overflow-tooltip
        >
          <template #default="{ row }: TableItem">
            <ui-amount :num="row.Amount" />
          </template>
        </el-table-column>
        <el-table-column align="center" label="申请方式" min-width="90">
          <template #default="{ row }: TableItem">
            <el-button :type="payTypeMap[row.PayType || 0].type" size="small">
              {{ payTypeMap[row.PayType || 0].text }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column align="center" label="状态" min-width="90">
          <template #default="{ row }: TableItem">
            <el-button :type="statusMap[row.Status || 0].type" size="small">
              {{ statusMap[row.Status || 0].text }}
            </el-button>
          </template>
        </el-table-column>
        <el-table-column label="申请时间" width="170" align="center">
          <template #default="{ row }: TableItem">
            {{ row.CreatedAt }}
          </template>
        </el-table-column>
        <el-table-column label="审核时间" width="170" align="center">
          <template #default="{ row }: TableItem">
            {{ row.UpdatedAt }}
          </template>
        </el-table-column>
        <el-table-column label="操作人" align="center">
          <template #default="{ row }: TableItem">
            {{ row.Issuer }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" align="center">
          <template #default="{ row }: TableItem">
            <el-button
              type="success"
              size="small"
              v-if="row.Status == 1 && premsStore.isApplyUpdown"
              @click="handleVerify(row.Id, true, '通过')"
            >
              通过
            </el-button>
            <el-button
              type="danger"
              size="small"
              v-if="row.Status == 1 && premsStore.isApplyUpdown"
              @click="handleVerify(row.Id, false, '驳回')"
            >
              拒绝
            </el-button>
            <el-button type="primary" size="small" @click="handleDetail(row.UserId)">
              详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="flex justify-end my-[10px] mx-[15px]">
      <ui-pagination
        :total="state.total"
        v-model:pageSize="state.pageSize"
        v-model:currentPage="state.page"
        @current-change="getData"
      ></ui-pagination>
    </div>
    <MemberInfoDialog ref="memberInfoDialogRef" :uid="uid" />
  </div>
</template>
<script setup lang="ts">
import MemberInfoDialog from "./components/member-info-dialog.vue";
import moment from "moment";
import $bus from "@/utils/bus";
import { useList } from "@/hooks/useList";
import { getDateArray, disableFutureDates } from "@/utils/common";
import { ElMessageBox } from "element-plus";
import { message } from "@/utils/message";
import { reqUpdownList, reqUpdownPass, reqUpdownReject } from "@/api/apply";
import { usePremsStore } from "@/store/modules/prems";

interface TableItem {
  row: UpdownItemMo;
}
const premsStore = usePremsStore();
const selectDate = ref<string>("today");
const getDate = () => {
  const date: Record<string, string[]> = getDateArray();
  return date;
};
const form = reactive({
  name: "",
  status: 0,
  type: 0,
  date: <string[] | "">getDateArray()["today"]
});
const statusType = [
  { name: "全部状态", value: 0 },
  { name: "审核中", value: 1 },
  { name: "已通过", value: 2 },
  { name: "已驳回", value: 3 }
];
const updownType = [
  { name: "全部类型", value: 0 },
  { name: "上分", value: 1 },
  { name: "下分", value: 2 }
];
const typeMap: Record<string, TextType> = {
  1: { text: "上分", type: "success" },
  2: { text: "下分", type: "danger" }
};
const payTypeMap: Record<string, TextType> = {
  0: { text: "后台上分", type: "success" },
  1: { text: "微信", type: "success" },
  2: { text: "支付宝", type: "primary" },
  3: { text: "银行卡", type: "info" },
  4: { text: "虚拟币", type: "warning" }
};
const statusMap: Record<string, TextType> = {
  1: { text: "待审核", type: "primary" },
  2: { text: "已通过", type: "success" },
  3: { text: "已驳回", type: "danger" }
};
const uid = ref<number>();
const memberInfoDialogRef = ref();
const getParams = () => {
  const params: any = {};

  if (form.type) {
    params.Type = form.type;
  }
  if (form.status) {
    params.Status = form.status;
  }
  if (form.name) {
    params.Name = form.name;
  }
  if (form.date) {
    params.StartDate = moment(form.date[0]).format("YYYY-MM-DD 00:00:00");
    params.EndDate = moment(form.date[1]).format("YYYY-MM-DD 23:59:59");
  }
  return params;
};
const { elTableRef, state, list, getData, search } = useList<UpdownItemMo, any>(
  reqUpdownList,
  getParams
);
// 重置
const handleRefresh = () => {
  selectDate.value = "";
  form.name = "";
  form.status = 0;
  form.type = 0;
  form.date = getDateArray()["today"];
  selectDate.value = "today";
  search();
};

const handleBtnDate = (str: string) => {
  const date = getDate();
  selectDate.value = str;
  form.date = date[str];
  search();
};

const handleVerify = (id: number, flag: boolean, text: string) => {
  ElMessageBox.confirm(`是否进行【${text}】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          if (flag) {
            await reqUpdownPass(id);
            message.success("申请已通过");
          } else {
            await reqUpdownReject(id);
            message.success("申请已驳回");
          }
          getData();
          instance.confirmButtonLoading = false;
          done(); // 操作成功后关闭对话框
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

const handleDetail = (id: number) => {
  uid.value = id;
  nextTick(() => {
    memberInfoDialogRef.value.open();
  });
};

onMounted(() => {
  getData();
  // 监听更新上下分消息
  $bus.on("update-updown-msg", () => {
    handleRefresh();
  });
});
onBeforeUnmount(() => {
  $bus.off("update-updown-msg");
});
</script>
<style lang="scss" scoped></style>
